import React, { Component } from 'react';
// 倒计时 for react
export default class Counter extends React.Component {
    // 定义属性
    static propTypes={
        onStep:React.PropTypes.func,
        onComplete:React.PropTypes.func,
        value:React.PropTypes.number,
        step:React.PropTypes.number
    }


    //这里面的操作可以移动到componentWillMount()里面去
    constructor(...pa) {
        super(...pa);
        this.initValue = parseInt(this.props.value) || 10;
        this.state     = {
            count: this.initValue,
            houre : parseInt(this.initValue / 3600),
            minute : parseInt((this.initValue - parseInt(this.initValue / 3600) * 3600) / 60),
            second : this.initValue - parseInt(this.initValue / 3600) * 3600 - parseInt((this.initValue - parseInt(this.initValue / 3600) * 3600) / 60) * 60
        };
        this.interval  = 0;
        this.step      = parseInt(this.props.step) || 1;
    }

    stop() {
        clearInterval(this.interval);
    }

    start() {
        this.stop();
        this.interval = setInterval(()=> {
            var count = this.state.count - this.step;
            if (this.props.onStep) {
                this.props.onStep(count);
            }
            if (count ==0) {
                this.props.onComplete && this.props.onComplete();
                this.stop();
            }else{
                this.setState({
                    count : count,
                    houre : parseInt(count / 3600),
                    minute : parseInt((count - parseInt(count / 3600) * 3600) / 60),
                    second : count - parseInt(count / 3600) * 3600 - parseInt((count - parseInt(count / 3600) * 3600) / 60) * 60
                });
            }
        }, 1000);
    }

    restart() {
        this.stop();
        this.setState({count: this.initValue});
        this.start();
    }
    componentDidMount(){
        this.start();
    }
    componentWillUnmount(){
        this.stop();
    }

    render() {
        return (
            <span>
                {this.state.houre >=10?this.state.houre:'0'+this.state.houre}:{this.state.minute >= 10?this.state.minute : '0'+this.state.minute}:{this.state.second >= 10?this.state.second : '0'+this.state.second}
            </span>
        )
    }
}